package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.ReviewDao;
import com.lei.springbootpractice.pojo.ReviewPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ReviewService {
    @Autowired
    private ReviewDao reviewDao;

    @Transactional
    public boolean createReview(ReviewPojo review) {
        if (review.getCreateTime() == null) {
            review.setCreateTime(LocalDateTime.now());
        }
        return reviewDao.insert(review) > 0;
    }

    public List<ReviewPojo> getReviewsByProductId(String productId) {
        return reviewDao.selectList(new QueryWrapper<ReviewPojo>()
            .eq("product_id", productId)
            .orderByDesc("create_time"));
    }

    public double getAverageRating(String productId) {
        Double avg = reviewDao.selectAvgRating(productId);
        return avg != null ? avg : 0.0;
    }

    public List<ReviewPojo> getReviewsByUser(String userId) {
        return reviewDao.selectList(new QueryWrapper<ReviewPojo>()
            .eq("user_id", userId)
            .orderByDesc("create_time"));
    }

    /**
     * 检查用户是否已评价某个订单中的特定商品 (通过 productId 和 orderId 联合判断)。
     *
     * @param userId 用户ID
     * @param productId 商品ID
     * @param orderId 订单ID
     * @return 如果已评价，返回true；否则返回false
     */
    public boolean hasUserReviewedProductInOrder(String userId, String productId, String orderId) {
        QueryWrapper<ReviewPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("order_id", orderId); // 使用 order_id 进行精确查询
        return reviewDao.selectCount(queryWrapper) > 0;
    }

    /**
     * 获取某个订单的所有评价记录。
     *
     * @param orderId 订单ID
     * @return 订单对应的所有评价列表
     */
    public List<ReviewPojo> getReviewsByOrderId(String orderId) {
        QueryWrapper<ReviewPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId); // 根据 order_id 查询
        // 你可能还想根据创建时间或其他相关字段排序
        // queryWrapper.orderByDesc("create_time");
        return reviewDao.selectList(queryWrapper);
    }
}